package skeleton

const templateCmdExec = `package cmd

import (
	"{{.Name}}/config"
	"fmt"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"os"
)

var (
	rootCmd       = &cobra.Command{}
	cfgFile       string
	cfgServerName string
)

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		_, _ = fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "config_local.yaml", "config file")
	rootCmd.PersistentFlags().StringVar(&cfgServerName, "server-name", "xiaoheiwu", "ServerName")

	rootCmd.AddCommand(apiServerCommand)   // API服务
}

func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	}

	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err != nil {
		_, _ = fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	// 初始化配置文件
	config.Cfg = config.NewDefaultConfig(nil)
	config.Cfg.ConfigFile = viper.ConfigFileUsed()
	config.Cfg.ServerName = cfgServerName
}
`

const templateCmdNewApiServer = `package cmd

import (
	"{{.Name}}/common"
	"{{.Name}}/config"
	"{{.Name}}/internal/router"
	"context"
	"fmt"
	nested "github.com/antonfisher/nested-logrus-formatter"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"gitlab.heywoods.cn/go-sdk/omega/component/log"
	"os"
	"runtime"
	"strings"
)

func init() {
	var getServeDir = func(path string) string {
		var run, _ = os.Getwd()
		return strings.Replace(path, run, ".", -1)
	}
	var formatter = &nested.Formatter{
		NoColors:        false,
		HideKeys:        true,
		TimestampFormat: "2006-01-02 15:04:05",
		CallerFirst:     true,
		CustomCallerFormatter: func(f *runtime.Frame) string {
			s := strings.Split(f.Function, ".")
			funcName := s[len(s)-1]
			return fmt.Sprintf(" [%s:%d][%s()]", getServeDir(f.File), f.Line, funcName)
		},
	}
	logrus.SetFormatter(formatter)
	logrus.SetReportCaller(true)
}

var (
	apiServerCommand = &cobra.Command{
		Use:   "api",
		Short: "start api server",
		Long:  "start api server",
		Run: func(cmd *cobra.Command, args []string) {
			//init server
			srv, err := router.NewRouter(config.Cfg)
			if err != nil {
				common.Logger.Error(context.Background(), "startService:1", log.String("err", err.Error()))
				os.Exit(1)
			}

			err = srv.InitRouter()
			if err != nil {
				common.Logger.Error(context.Background(), "startService:2", log.String("err", err.Error()))
				os.Exit(1)
			}
		},
	}
)
`
